#import "InstructionsTipsView.h"
#import "SVProgressHUD.h"
#import <WebKit/WebKit.h>

@interface InstructionsTipsView ()

@property (weak, nonatomic) IBOutlet UIView *webBGView;
@property (strong, nonatomic) WKWebView *wkWeb;
@property(nonatomic,strong) WKWebViewConfiguration *wkWebConfig;

@end


@implementation InstructionsTipsView


+ (instancetype) loadInstructionsTipsView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"InstructionsTipsView" owner:nil options:nil]firstObject];
}


- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initWebViewWithURLStr:ServiceAgreement superView:self.webBGView];
}


- (IBAction)disagreeClick:(UIButton *)sender {
    [self removeFromSuperview];
    if (_disagreeBlock) {
        _disagreeBlock();
    }
}


- (IBAction)agreeClick:(UIButton *)sender {
    [self removeFromSuperview];
    if (_agreeBlock) {
        _agreeBlock();
    }
}


- (void)initWebViewWithURLStr:(NSString *)urlStr superView:(UIView *)superView{
    [superView addSubview:self.wkWeb];
    [self.wkWeb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
    if ([urlStr containsString:@"http"] || [urlStr containsString:@"https"]) {
        [self.wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    }else{
        NSString *filePath = [[NSBundle mainBundle] pathForResource:urlStr ofType:nil];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.wkWeb loadRequest:request];
    }
}

#pragma mark - lazy
- (WKWebView *)wkWeb{
    if (!_wkWeb) {
        _wkWeb = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.wkWebConfig];
        _wkWeb.opaque = NO;
        _wkWeb.backgroundColor = CLEARCOLOR;
        _wkWeb.scrollView.backgroundColor = CLEARCOLOR;
        _wkWeb.scrollView.showsHorizontalScrollIndicator = NO;
        _wkWeb.scrollView.showsVerticalScrollIndicator = NO;
    }
    return _wkWeb;
}

-(WKWebViewConfiguration *)wkWebConfig {
    if (!_wkWebConfig) {
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        _wkWebConfig = [[WKWebViewConfiguration alloc] init];
        _wkWebConfig.userContentController = wkUController;
    }
    return _wkWebConfig;
}
@end
